package hxg.thread.readwritelock;


import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;


/**
 * @author HeXiangGuang
 * @create 2021-06-24 17:55
 * ReentrantReadWriteLock:
 *  一种支持一写多读的同步锁，读写分离，可分别分配读锁、写锁。·支持多次分配读锁，使多个读操作可以并发执行。
 * 互斥规则:
 * 。写-写:互斥，阻塞。
 * 。读,写:互斥，读阻塞写、写阻塞读。。读-读:不互斥、不阻塞。
 * ·在读操作远远高于写操作的环境中，可在保障线程安全的情况下，提高运行效率。
 */
public class ReadWriteDemo {
    //创建读写锁
    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    //获取读锁
    private ReadLock readLock =  rwl.readLock();
    //获取写锁
    private WriteLock writeLock = rwl.writeLock();
    private String value;
    //读方法

    public String getValue() throws InterruptedException {
        //开启读锁
        readLock.lock();
        try {
            Thread.sleep(1000);
            System.out.println("读入" + value);
        } finally {
            readLock.unlock();
        }
        return this.value;
    }

    //写方法


    public void setValue(String value) throws InterruptedException {
        //开启写锁
        writeLock.lock();
        try {
            Thread.sleep(1000);
            this.value = value;
            System.out.println("写入" + value);
        } finally {
            writeLock.unlock();
        }
    }



}
